<template>
  <div>
    <!-- 联系人卡片 -->
    <van-contact-card
      :type="cardType"
      :name="currentContact.name"
      :tel="currentContact.tel"
      @click="showList = true"
    />

    <!-- 联系人列表 -->
    <!--数据双向绑定-->
    <van-popup v-model="showList" position="bottom">
      <van-contact-list
        v-model="chosenContactId"
        :list="list"
        @add="onAdd"
        @edit="onEdit"
        @select="onSelect"
      />
    </van-popup>

    <!-- 联系人编辑 -->
    <van-popup v-model="showEdit" position="bottom">
      <van-contact-edit
        :contact-info="editingContact"
        :is-edit="isEdit"
        :tel-validator="()=>true"
        @save="onSave"
        @delete="onDelete"
      />
    </van-popup>

  </div>
</template>

<script>
  /*1. 分析计算属性 及其 依赖
*
*   cardType
*       chosenContactId
*   currentContact
*       chosenContactId
*       list
* */
  import {mapState,mapGetters,mapActions} from "vuex"
  import { ContactCard, ContactList, ContactEdit,Popup  } from 'vant';
  const OK = 200;
  export default {
    name: 'contact',
    data() {
      return {
        showList: false, //控制cardList能否显示
        showEdit: false, //控制cardEdit能否显示
      };
    },
    computed: {
      ...mapState(["editingContact","isEdit","list"]),
      ...mapGetters(["cardType","currentContact"]),
      chosenContactId:{
        get(){
          return this.$store.state.chosenContactId;
        },
        set(val){
          this.$store.commit("updateChosenContactId",val)
        }
      }
    },
    methods: {
      /* saveForAdd(obj){
        this.$store.dispacth("saveForAdd",obj)
      }*/
      ...mapActions(["updateList","add","edit","delete","saveForAdd","saveForEdit"]),

      // 添加联系人
      onAdd() {
        //将编辑页显示出来
        this.showEdit = true;
        this.add()
      },

      // 编辑联系人
      onEdit(item) {
        //item:当前联系人对象
        //将编辑页显示出来
        this.showEdit = true;
        this.edit(item)
      },

      // 选中联系人
      onSelect() {
        //将list组件隐藏起来
        this.showList = false;
        //chosenContactId也会被改变
      },

      // 保存联系人
      async onSave(info) {
        //info : 表单内容
        //将list edit页全部关掉
        this.showEdit = false;
        this.showList = false;
        //this.isEdit 控制是否出现删除按钮
        if (this.isEdit)
          this.saveForEdit(info)//修改逻辑
        else
          this.saveForAdd(info)//新增逻辑
      },

      // 删除联系人
      async onDelete(info) {
        //将编辑组件隐藏起来
        this.showEdit = false;
        //实现删除功能
        this.delete(info)
      },
    },
    components:{
      [ContactCard.name]:ContactCard,
      [ContactList.name]:ContactList,
      [ContactEdit.name]:ContactEdit,
      [Popup.name]:Popup
    },
    created(){
        //转发一个action 在action中发请求获取数据 在action获取数据后 通过mutation来修改state
        this.updateList()
    }
  }
</script>

<style scoped>

</style>
